package com.whmnx.main.ui.model;

import android.app.Application;
import android.content.Intent;
import android.text.TextUtils;
import android.view.View;

import androidx.annotation.NonNull;
import androidx.databinding.ObservableArrayList;
import androidx.databinding.ObservableList;
import androidx.recyclerview.widget.DefaultItemAnimator;
import androidx.recyclerview.widget.GridLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import com.classic.adapter.CommonRecyclerAdapter;
import com.tencent.qcloud.ugckit.UGCKitConstants;
import com.whmnx.base.bean.BaseBean;
import com.whmnx.base.bean.PersonalBean;
import com.whmnx.base.bean.TCVideoInfo;
import com.whmnx.base.bean.VideoListBean;
import com.whmnx.base.constants.Constants;
import com.whmnx.base.constants.EventConstants;
import com.whmnx.base.http.CallBack;
import com.whmnx.base.http.HttpClient;
import com.whmnx.base.utils.ImageUtil;
import com.whmnx.main.BR;
import com.whmnx.main.R;
import com.whmnx.main.databinding.ActivityPersonal2Binding;
import com.whmnx.main.ui.activity.PersonalActivity2;
import com.whmnx.main.ui.adapter.VedioAdapter3;
import com.whmnx.main.ui.videorecord.TCVodPlayerActivity;

import java.io.Serializable;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import me.goldze.mvvmhabit.base.BaseViewModel;
import me.goldze.mvvmhabit.binding.command.BindingAction;
import me.goldze.mvvmhabit.binding.command.BindingCommand;
import me.goldze.mvvmhabit.bus.RxBus;
import me.goldze.mvvmhabit.utils.SPUtils;
import me.tatarka.bindingcollectionadapter2.ItemBinding;

/**
 * author : huang
 * date   : 2020/10/26 0026 16:20
 * version: 1.0
 * @author Administrator
 */
public class PersonalModel2 extends BaseViewModel {
    public PersonalActivity2 mActivity;
    public ActivityPersonal2Binding mBinding;
    public List<TCVideoInfo> mTCLiveInfoList  = new ArrayList<>();

    private List<VideoListBean> videoListBean = new ArrayList<>();

    private int page = 1;
    private int pageSize = 10;
    private int type2;
    private String uId;
    private VedioAdapter3 vedioAdapter;

    public PersonalModel2(@NonNull Application application) {
        super(application);
    }

    public BindingCommand OnClickCommand = new BindingCommand(new BindingAction() {
        @Override
        public void call() {
          finish();
        }
    });
    public BindingCommand OnClickCommand2 = new BindingCommand(new BindingAction() {
        @Override
        public void call() {
            type2 = 0;
            page = 1;
            getMyworklist(true,0);
            mBinding.tv1.setTextColor(mActivity.getResources().getColor(R.color.black));
            mBinding.tv2.setTextColor(mActivity.getResources().getColor(R.color.textColorGray2));
        }
    });
    public BindingCommand OnClickCommand3 = new BindingCommand(new BindingAction() {
        @Override
        public void call() {
            type2 = 1;
            page = 1;
            getMyworklist(true,1);

            mBinding.refresh.setOnRefreshListener(refreshLayout -> getMyworklist(true,type2));
            mBinding.refresh.setOnLoadMoreListener(refreshLayout -> getMyworklist(false,type2));
            mBinding.tv1.setTextColor(mActivity.getResources().getColor(R.color.textColorGray2));
            mBinding.tv2.setTextColor(mActivity.getResources().getColor(R.color.black));
        }
    });
    //关注
    public BindingCommand OnClickCommand4 = new BindingCommand(new BindingAction() {
        @Override
        public void call() {
            if (mBinding.tv.getText().toString().contains("+")){  //加关注
                addFollow(Constants.ADDFOLLOW);
            }else {
                addFollow(Constants.CANCELFOLLOW);
            }
        }
    });

    private void addFollow(String url) {
        Map<String, Object> params = new HashMap<>();
        if (TextUtils.isEmpty(mActivity.getIntent().getStringExtra("uId"))){
            params.put("FollowUserId",SPUtils.getInstance().getString("uuid"));
        }else {
            params.put("FollowUserId",mActivity.getIntent().getStringExtra("uId"));
        }
            params.put("UserId", SPUtils.getInstance().getString(Constants.USERID));

        HttpClient.get(mActivity, url, params,new CallBack<BaseBean>() {
            @Override
            public void onSuccess(BaseBean baseBean) {
                if (url.equals(Constants.ADDFOLLOW)){
                    mBinding.tv.setText("已关注");
                }else {
                    mBinding.tv.setText("+ 关注");
                }
                RxBus.getDefault().post(EventConstants.FOLLOW);
            }
        });
    }

    public void initToolbar(PersonalActivity2 personalActivity, ActivityPersonal2Binding binding) {
        this.mActivity = personalActivity;
        this.mBinding = binding;

        GridLayoutManager gridLayoutManager = new GridLayoutManager(mActivity, 3);
        //设置RecycleView显示的方向是水平还是垂直 GridLayout.HORIZONTAL水平  GridLayout.VERTICAL默认垂直
        //配置布局，默认为vertical（垂直布局），下边这句将布局改为水平布局
        //  layoutManager.setOrientation(LinearLayoutManager.VERTICAL);
        // gridLayoutManager.setOrientation(GridLayout.VERTICAL);
        mBinding.rv.setLayoutManager(gridLayoutManager);
        mBinding.rv.setItemAnimator(new DefaultItemAnimator());
        vedioAdapter = new VedioAdapter3(mActivity);
        mBinding.rv.setAdapter(vedioAdapter);


        initData();


        getMyworklist(true,0);

    }



    private void initData() {
        uId = mActivity.getIntent().getStringExtra("uId");
        if (!TextUtils.isEmpty(mActivity.getIntent().getStringExtra("uId"))){
            int isFocus =  mActivity.getIntent().getIntExtra("IsFocus",0);
            if (isFocus == 0){
                mBinding.tv.setText("+ 关注");
            }else {
                mBinding.tv.setText("已关注");
            }
        }else {
            int isFocus =  Constants.ISFOCUS;
            if (isFocus == 0){
                mBinding.tv.setText("+ 关注");
            }else {
                mBinding.tv.setText("已关注");
            }
        }


        Map<String, Object> params = new HashMap<>();
        if (TextUtils.isEmpty(mActivity.getIntent().getStringExtra("uId"))){
            params.put("uId",SPUtils.getInstance().getString("uuid"));
        }else {
            params.put("uId",mActivity.getIntent().getStringExtra("uId"));
        }
        HttpClient.get(mActivity, Constants.PERSONALINFORMATION, params,new CallBack<PersonalBean>() {
            @Override
            public void onSuccess(PersonalBean personalBean) {
                ImageUtil.setImage(mBinding.ivLocation,personalBean.getUserInfo_HeadImg());
                mBinding.tvName.setText(personalBean.getUserInfo_NickName());
                mBinding.tvFan.setText("粉丝  " + personalBean.getFansNum() + "    关注  " + personalBean.getFocusNum());
            }
        });
    }

    private void getMyworklist(boolean isRefresh,int type) {
        if (isRefresh) page = 1;
        Map<String, Object> params = new HashMap<>();
       if (TextUtils.isEmpty(uId)){
            params.put("userId",SPUtils.getInstance().getString("uuid"));
        }else {
            params.put("userId",uId);
        }
        params.put("type", type);
        params.put("pageIndex",page);
        params.put("pageSize", pageSize);
        HttpClient.post(mActivity, Constants.MYWORKLIST, params,new CallBack<List<VideoListBean>>() {
            @Override
            public void onSuccess(List<VideoListBean> videoBeans) {
              /*  if (isRefresh){
                    observableList.clear();
                    if (videoBeans.size()>0) {
                        observableList.clear();
                        mBinding.llEmpty.setVisibility(View.GONE);
                        for (int i = 0; i < videoBeans.size(); i++) {
                            TCVideoInfo tcVideoInfo = new TCVideoInfo();
                            tcVideoInfo.playurl = videoBeans.get(i).getWork_Vidoe();
                            mTCLiveInfoList.add(tcVideoInfo);
                            observableList.add(new WorkItemViewModel3(PersonalModel.this, videoBeans.get(i), i));
                        }
                    }else {
                        observableList.clear();
                        mBinding.llEmpty.setVisibility(View.VISIBLE);
                    }

                    mBinding.refresh.finishRefresh(true);
                }else {
                    if (videoBeans.size() > 0) {
                        for (int i = 0; i < videoBeans.size(); i++) {
                            TCVideoInfo tcVideoInfo = new TCVideoInfo();
                            tcVideoInfo.playurl = videoBeans.get(i).getWork_Vidoe();
                            mTCLiveInfoList.add(tcVideoInfo);
                            observableList.add(new WorkItemViewModel3(PersonalModel.this, videoBeans.get(i), i));
                        }
                        mBinding.refresh.finishLoadMore(true);
                    } else {
                        mBinding.refresh.finishLoadMoreWithNoMoreData();
                    }
                }*/

                mTCLiveInfoList.clear();
                videoListBean.clear();
                videoListBean.addAll(videoBeans);
                for (int i = 0; i < videoBeans.size(); i++) {
                    TCVideoInfo tcVideoInfo = new TCVideoInfo();
                    tcVideoInfo.playurl = videoBeans.get(i).getWork_Vidoe();
                    mTCLiveInfoList.add(tcVideoInfo);
                    //  observableList.add(new WorkItemViewModel(WorksModel.this,videoBeans.get(i),i));
                }
                if (isRefresh) {
                    if (videoBeans.size() == 0){
                        mBinding.llEmpty.setVisibility(View.VISIBLE);
                        mBinding.rv.setVisibility(View.GONE);
                    }else {
                        mBinding.llEmpty.setVisibility(View.GONE);
                        mBinding.rv.setVisibility(View.VISIBLE);
                    }

                    mBinding.refresh.finishRefresh(true);
                    vedioAdapter.replaceAll(videoBeans, true);
                    //   workListTopAdapter.replaceAll(result, true);
                } else {
                    if (videoBeans.size() > 0) {
                        mBinding.refresh.finishLoadMore(true);
                        vedioAdapter.addAll(videoBeans);
                    } else {
                        mBinding.refresh.finishLoadMoreWithNoMoreData();
                    }
                }
                page++;
            }
        });


        vedioAdapter.setOnItemClickListener(new CommonRecyclerAdapter.OnItemClickListener() {
            @Override
            public void onItemClick(RecyclerView.ViewHolder viewHolder, View view, int i) {
                Intent intent = new Intent(mActivity, TCVodPlayerActivity.class);
                intent.putExtra(UGCKitConstants.PLAY_URL, vedioAdapter.getItem(i).getWork_Vidoe());
                intent.putExtra(UGCKitConstants.PUSHER_ID, 2);
                //  intent.putExtra(UGCKitConstants.PUSHER_NAME, item.nickname == null ? item.userid : item.nickname);
                intent.putExtra(UGCKitConstants.PUSHER_AVATAR, vedioAdapter.getItem(i).getWork_Image());
                intent.putExtra(UGCKitConstants.COVER_PIC, vedioAdapter.getItem(i).getWork_Image());
                intent.putExtra(UGCKitConstants.FILE_ID, "");
                intent.putExtra(UGCKitConstants.TCLIVE_INFO_LIST, (Serializable) mTCLiveInfoList);
                intent.putExtra(UGCKitConstants.TIMESTAMP, (Serializable) videoListBean);
                intent.putExtra(UGCKitConstants.TCLIVE_INFO_POSITION, i);
                mActivity.startActivityForResult(intent, 100);
            }
        });
    }


    //给RecyclerView添加ObservableList
    public ObservableList observableList = new ObservableArrayList<>();
    //给RecyclerView添加ItemBinding
    public ItemBinding<WorkItemViewModel3> itemBinding = ItemBinding.of(BR.viewModel, R.layout.item_work2);
}
